<?php
/**
 * File: FileController.php
 * User: lyc
 * Date: 16/3/27
 * Time: 下午4:46
 */

namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Auth;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Input;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Worksheet;
use DB;
use Hash;
use Illuminate\Support\Str;
use Cache;
use Illuminate\Support\Facades\File;
use ZipArchive;
use Parsedown;



class FileController extends Controller
{
    private $timuall = array();

    public function upload(Request $request)
    {
        $file = $request->file('myfile');
        $file2 = $request->file('myfile2');
        $askCode = $this->getRandStr(6);
        $clientName = $file->getClientOriginalName();
        $tmpName = $file->getFileName();
        $realPath = $file->getRealPath();
        $entension = $file->getClientOriginalExtension();
        $mimeType = $file->getClientMimeType();
        $clientName2 = $file2->getClientOriginalName();
        $tmpName2 = $file2->getFileName();
        $realPath2 = $file2->getRealPath();
        $entension2 = $file2->getClientOriginalExtension();
        $mimeType2 = $file2->getClientMimeType();
        $path = $file->move('upload_files', $clientName);
        $path2 = $file2->move('upload_files', $clientName2);
        if ($entension == 'xls' || $entension == 'xlsx' || $entension2 == 'xls' || $entension2 == 'xlsx') {

            //获取学生名单文件
            $filename = public_path() . '/' . $path;
            if($entension == 'xlsx') {
                $objExcelReader = PHPExcel_IOFactory::createReader("Excel2007");
            }else if($entension == "xls") {
                $objExcelReader = PHPExcel_IOFactory::createReader("Excel5");
            }
            $objPHPExcel = $objExcelReader->load($filename);
            $sheet = $objPHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();           //取得总行数
            $highestColumn = $sheet->getHighestColumn(); //取得总列数
            $objPHPExcel->setActiveSheetIndex(0);
            $i = 0;
            $expiresAt = Carbon::now()->addMinutes(600);
            $objWorksheet = $objPHPExcel->getActiveSheet();

            //获取题目文件
            $filename2 = public_path() . '/' . $path2;
            if($entension2 == 'xlsx') {
                $objExcelReader2 = PHPExcel_IOFactory::createReader("Excel2007");
            }else if($entension2 == "xls") {
                $objExcelReader2 = PHPExcel_IOFactory::createReader("Excel5");
            }
            $objPHPExcel2 = $objExcelReader2->load($filename2);
            $sheet2 = $objPHPExcel2->getSheet(0);
            $objPHPExcel2->setActiveSheetIndex(0);
            $i2 = 0;
            $expiresAt2 = Carbon::now()->addMinutes(600);
            $objWorksheet2 = $objPHPExcel2->getActiveSheet();

            //读取题目文件存入Cache中
            $timudata = array();
            foreach ($objWorksheet2->getRowIterator() as $row2) {
                if ($i2 > 0) {
                    $j2 = 0;
                    $cellIterator2 = $row2->getCellIterator();
                    $cellIterator2->setIterateOnlyExistingCells(false);
                   // $arr=range('A','D');
                   // shuffle($arr);
		    $arr = ['A','B','C','D'];
                    foreach ($cellIterator2 as $cell2) {

                        if ($j2 == 0) {
                            $timudata = array("index" => $cell2->getValue());
                            $j2++;
                        } else if ($j2 == 1) {
                            $Parsedown = new \Parsedown();
                            $timudata['timu'] = $cell2->getValue();
                            $markdownMode = $Parsedown->text($timudata['timu']);
                            $timudata['timu'] = $markdownMode;
                            $j2++;
                        } else if ($j2 == 2) {
                            $timudata[$arr[0]] = $cell2->getValue();
                            $j2++;
                        } else if ($j2 == 3) {
                            $timudata[$arr[1]] = $cell2->getValue();
                            $j2++;
                        } else if ($j2 == 4) {
                            $timudata[$arr[2]] = $cell2->getValue();
                            $j2++;
                        } else if ($j2 == 5) {
                            $timudata[$arr[3]] = $cell2->getValue();
                            $j2++;
                        } else if ($j2 == 6) {
                            // $Parsedown = new \Parsedown();
                            $timudata['correctAnswer'] = $cell2->getValue();
                            // $markdownMode = $Parsedown->text($timudata['correctAnswer']);
                            // $timudata['correctAnswer'] = $markdownMode;
                            $j2++;
                        }

                    }
                    // $arr=range('A','D');
                    // $arrs = range('A','D');
                    // shuffle($arr);
                    // $arri = 0;
                    // foreach ($arr as $values)
                    // {
                    //     if($arri%2 == 0) {
                    //         $arri++;
                    //         continue;
                    //     }
                    //     $temp = $timudata[$arrs[$arri]];
                    //     $timudata[$arrs[$arri]] = $timudata[$values];
                    //     $timudata[$values] = $temp;
                    //     $arri++;
                    // }
                    if($timudata['timu']!=null)
                    {
                        $this->timuall[$i2] = $timudata;
                    }
                 
                }
                $i2++;
             //var_dump($timudata);
            }
            

            if (!Cache::has($askCode . '_timu')) {
                Cache::add($askCode . '_timu', $this->timuall, $expiresAt2);
            } else {

            }

            //读取学生文件存入Cache中
            $stunum = "";
            $stuname = "";
            $userdata = array();
            foreach ($objWorksheet->getRowIterator() as $row) {

                if ($i > 0) {
                    $j = 0;
                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(false);
                    foreach ($cellIterator as $cell) {
                        if($j == 0) {
                            $stunum = (string)$cell;
                            $j++;
                        }else if($j == 1){
                            $stuname = (string)$cell;
                            $j++;
                        }
                    }
                    $userdata[$stunum] = $stuname;
                }
                $i++;

            }
            if (!Cache::has($askCode . '_stu')) {
                Cache::add($askCode . '_stu', $userdata, $expiresAt);
            } else {

            }
        }else{
            return response()->json(["error" => "文件格式错误"]);
        }
        $expiresTime = Carbon::now()->addMinutes(600);
        $options["mode"] = 1;
        Cache::put($askCode."_option",$options,$expiresTime);
        return response()->json(["askCode" => $askCode,"mode"=>$options["mode"]]);
    }

    //得到随机数组
    public function getRandStr($length) {
		$str = '0123456789';
        //$str = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randString = '';
        $len = strlen($str)-1;
        for($i = 0;$i < $length;$i ++){
            $num = mt_rand(0, $len);
            $randString .= $str[$num];
        }
        return $randString;
    }

    //存入xlsx文件中
    public function saveWithXlsx(Request $request){
        //设定时区
        date_default_timezone_set('PRC');
        $askCode = $request->input('askCode');
        $index = 1;
        $resultPHPExcel = new PHPExcel();

        $stuALL = Cache::get($askCode.'_stu');
        $resultWorksheet = $resultPHPExcel->getActiveSheet(0);
        $resultWorksheet->setCellValue('A1', '学号');
        $resultWorksheet->setCellValue('B1', '姓名');
        $resultWorksheet->setCellValue('C1', '题号');
        $resultWorksheet->setCellValue('D1', '选项');
        $resultWorksheet->setCellValue('E1', '答案');
        $resultWorksheet->setCellValue('F1', '是否正确');
        $resultWorksheet->setCellValue('G1', '更多答案');
        $resultWorksheet->setCellValue('H1', '答题时间');
        $resultWorksheet->getColumnDimension('A')->setWidth(10);
        $resultWorksheet->getColumnDimension('G')->setWidth(18);

        $timuCount = count(Cache::get($askCode.'_timu'));
        $i = 2;
        for($jj = 0; $jj < $timuCount; $jj++){
            $answerResult = Cache::get($askCode . '_answer_'.$index);
            if($answerResult != null) {
                foreach ($answerResult as $answer) {
                    $resultWorksheet->setCellValue('A'.$i, $answer['stuid']);
                    $resultWorksheet->setCellValue('B'.$i, $stuALL[$answer['stuid']]);
                    $resultWorksheet->setCellValue('C'.$i, $answer['index']);
                    $resultWorksheet->setCellValue('D'.$i, $answer['chooses']);
                    $resultWorksheet->setCellValue('E'.$i, $answer['answer']);
                    $resultWorksheet->setCellValue('F'.$i, $answer['isCorrect']);
                    $resultWorksheet->setCellValue('G'.$i, $answer['moreAnswer']);
                    $resultWorksheet->setCellValue('H'.$i, date('Y-m-d H:i:s',$answer['answerTime']));
                    $i++;
                }
            }
            $resultPHPExcel->getActiveSheet($index-1)->setTitle('答题结果'.$index);
            $index++;
        }
        $objWriter = PHPExcel_IOFactory::createWriter($resultPHPExcel, 'Excel2007');
        $outputFileName = $askCode.'_answerResult.xlsx';
        $objWriter->save('download_files/'.$outputFileName);
        $filename = 'download_files/'.$outputFileName;

        //下载文件,Response Header
		header("Content-Type:application/octet-stream");
        header("Content-Disposition: attachment; filename=".$outputFileName);
        header("Expires:Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified:".Carbon::now()->format('D, d M Y H:i:s'));
        readfile($filename);

    }

}
